﻿using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Mvc;
using Microsoft.Data.Entity;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.PlatformAbstractions;
using Sino.CapacityCloud.Infrastructure.Filters;
using Sino.CapacityCloud.Repositories.Models;
using Sino.CapacityCloud.Services;
using Sino.CapacityCloud.WebApi.ViewModels;
using Sino.WebApi.Framework.Responses;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Sino.CapacityCloud.WebApi.ApiControllers
{

    //[Authorize(Roles = "Administrator")]
    public class WebApiCredentialController
        : ApiController<WebApiCredentialController>
    {

        private readonly IRandomPasswordService _randomPasswordService;

        public WebApiCredentialController(
            IHostingEnvironment env,
            IApplicationEnvironment applicationEnvironment,
            IDistributedCache cache,
            ITokenGenertationService tokenGenertationService,
            ApplicationDbContext dbContext,
            ApplicationUserManager userManager,
            ApplicationRoleManager roleManager,
            ApplicationSignInManager signInManager,
            ILoggerFactory loggerFactory, IRandomPasswordService randomPasswordService)
            : base(env, applicationEnvironment, cache, tokenGenertationService, dbContext, userManager, roleManager, signInManager, loggerFactory)
        {
            this._randomPasswordService = randomPasswordService;
        }

        public async Task<JsonResult> GetWebApiCredentials(int startIndex, int count = 10)
        {
            try
            {
                var response = new GetWebApiCredentialsResponse()
                {
                    WebApiCredentials = this.DataContext.WebApiCredentials.AsNoTracking().Select(x => new WebApiCredentialViewModel()
                    {
                        Id = x.WebApiCredentialId,
                        AppKey = x.AppKey,
                        AppSecrect = x.AppSecrect
                    }).Skip(startIndex).Take(count).ToArray()
                };
                return await this.PackageResultAsync<GetWebApiCredentialsResponse>(response);
            }
            catch (Exception ex)
            {
                this._logger.LogError($"Failed to get web api credentials because: {ex.Message + Environment.NewLine + ex.StackTrace}");
                return await this.PackageResultAsync<GetWebApiCredentialsResponse>(ex);
            }
        }

        [HttpPost]
        public async Task<JsonResult> AddWebApiCredential([FromBody]WebApiCredentialViewModel model)
        {
            try
            {
                this.DataContext.WebApiCredentials.Add(new WebApiCredential()
                {
                    AppKey = model.AppKey,
                    AppSecrect = model.AppSecrect
                });
                this.DataContext.SaveChanges();
                return await this.PackageResultAsync<VoidResponse>();
            }
            catch (Exception ex)
            {
                this._logger.LogError($"Failed to add web api credential with id={model.Id} & appKey={model.AppKey} & appSecerct={model.AppSecrect} because: {ex.Message + Environment.NewLine + ex.StackTrace}");
                return await this.PackageResultAsync<VoidResponse>(ex);
            }
        }

        public async Task<JsonResult> RemoveWebApiCredential(string id)
        {
            try
            {
                var credential = this.DataContext.WebApiCredentials.FirstOrDefault(x => x.WebApiCredentialId == id);
                if (credential != null)
                {
                    this.DataContext.WebApiCredentials.Remove(credential);
                    this.DataContext.SaveChanges();
                }
                return await this.PackageResultAsync<VoidResponse>();
            }
            catch (Exception ex)
            {
                this._logger.LogError($"Failed to delete web api credential with Id={id} because: {ex.Message + Environment.NewLine + ex.StackTrace}");
                return await this.PackageResultAsync<VoidResponse>(ex);
            }
        }

    }

}